package com.cy.pj.common.aspect;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SysCacheAspect {
	private Map<Object,Object> cache = new ConcurrentHashMap<>();
	/** 细粒度的切入点表达式 
	 * 基于@annotation(注解类全名)表达式定义切入点(这种切入点通常理解为细粒度的切入点)*/
	@Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
	public void doCache() {}
	
	@Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
	public void ClearCache() {}
	
	/*
	 * 	Get data from cache
		查询所有的部门信息
		Get data from cache over
	 */
	
	@AfterReturning("ClearCache()")
	public void clearCache() {
		System.out.println("Do Clear Cache");
		cache.remove("dept");
	}
	
	@Around("doCache()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("Get data from cache");
		Object result = cache.get("dept");
		//如何将cache中的key定义的更加灵活?在描述切入点的方法注解中直接指定key
		//如何获取切入点方法上的注解中的key?首先获取目标方法,再基于方法获取方法上的注解,在通过注解获取key的值
		if(result!=null) return result; 
		result = pjp.proceed();
		cache.put("dept", result);
		System.out.println("Get data from cache over");
		return result;
	}
	
}
